package com.happymall.demo2.filter;

import com.happymall.demo2.model.Permission;
import com.happymall.demo2.model.Role;
import com.happymall.demo2.model.User;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

public class UrlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = (User)req.getSession().getAttribute("user");
        if (user == null) {
            noAuth(req, response, "/login");
            return;
        }
        String url = req.getServletPath();
        for(Role role : user.getRoles()) {
            Set<Permission> permissionSet  = role.getPermissions();
            for(Permission permission : permissionSet) {
                if(url.equals(permission.getUrl())) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        noAuth(req, response, "/unauthorized");
        return;
    }

    @Override
    public void destroy() {
    }

    /**
     * 无权处理
     */
    public void noAuth(HttpServletRequest request, HttpServletResponse response, String noAuthPage) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        request.setAttribute("currentUrl", servletPath);
        String requestAccept = request.getHeader("accept");
        String contentType = "text/html";

        //判断请求类型
        if (StringUtils.isNotEmpty(requestAccept)) {
            if (StringUtils.contains(requestAccept, "application/json") || StringUtils.contains(requestAccept, "text/javascript") || StringUtils
                    .contains(requestAccept, "text/json")) {
                contentType = "application/json";
            }
        }
        response.setHeader("Content-Type", contentType + "; charset=UTF-8");
        clientRedirect(response, noAuthPage);
    }

    public static void clientRedirect(HttpServletResponse response, String path) throws IOException {
        response.setHeader("Content-Type", "text/html");
        response.getWriter().println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
                + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<head>\n" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>\n"
                + "<title>跳转中...</title>\n" + "</head>\n" + "<body>\n" + "跳转中，请稍候...\n" + "<script type=\"text/javascript\">//<![CDATA[\n"
                + "window.location.href='" + path + "?ret='+encodeURIComponent(window.location.href);\n" + "//]]></script>\n" + "</body>\n" + "</html>\n");
    }
}
